# coding=utf-8
from datetime import datetime


from sqlalchemy import Column
from sqlalchemy.types import CHAR, Integer, VARCHAR, BIGINT, DateTime

from app_admin.extensions.mysql.mysql_base import Base
from ..extensions.mysql.session import sessionCM


class Players(Base):
    __tablename__ = 'ibb_user'

    id = Column(Integer, autoincrement=True, nullable=False, unique=True, primary_key=True)
    name = Column(VARCHAR(255), index=True)  # or Column(String(30))
    nick_name = Column(VARCHAR(255), index=True)
    passwd = Column(CHAR(32))
    phone = Column(VARCHAR(20), index=True, default="")
    device_id = Column(VARCHAR(50))
    gold = Column(BIGINT)

    def __init__(self, passwd, name, nickname, device_id='', phone='', introduction=''):
        self.name = name
        self.nickname = nickname
        self.passwd = passwd
        self.phone = phone
        self.device_id = device_id
        self.gold = 0
        self.introduction = introduction

    def to_dict(self):
        return {"id": self.id, "name": self.name, "nick_name": self.nick_name,
                "gold": self.gold, "phone": self.phone, "modified_date": str(self.modified_date)}



    @classmethod
    def get_user_info_by_id(cls, user_id):
        with sessionCM() as session:
            player = session.query(Players).filter_by(id=user_id).first()
            return player.to_dict() if player else {}

    @classmethod
    def get_all_user_info(cls):
        ret = []
        with sessionCM() as session:
            players = session.query(Players).all()
            for i in players:
                ret.append(i.to_dict())
            return ret if players else []


    @classmethod
    def get_user_by_name(cls, user_name):
        with sessionCM() as session:
            player = session.query(Players).filter_by(name=user_name).first()
            return player.to_dict() if player else {}



    @classmethod
    def update_user_gold(cls, user_id, gold_change):
        with sessionCM() as session:
            player = session.query(Players).filter_by(id=user_id).first()
            if player:
                player.gold += gold_change
                session.commit()
                return 1, {"gold": player.gold}
            return 0, {}

    @classmethod
    def is_enough_gold(cls, user_name, change_gold):
        with sessionCM() as session:
            player = session.query(Players).filter_by(name=user_name).first()
            return (player.gold + change_gold) > 0

